package trafficAgent;

import java.util.ArrayList;
import java.util.List;

import org.jgrapht.graph.DefaultWeightedEdge;
import org.jgrapht.graph.SimpleDirectedWeightedGraph;

import model.Car;
import model.Crossroads;
import model.GraphUtility;
import model.Street;
import jade.core.behaviours.OneShotBehaviour;

public class ComputeBestRoute extends OneShotBehaviour {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	TrafficAgent agent; 
	SimpleDirectedWeightedGraph<Crossroads, DefaultWeightedEdge> graph;
	
	public ComputeBestRoute(final TrafficAgent myAgent) {
		super(myAgent);
		agent = (TrafficAgent) this.myAgent;
		graph = GraphUtility.genGraph(agent.getMap());
	}
	
	
	@Override
	
	public void action() {
		
		
		
		
		
		for(final Car c: agent.getMap().getCars()){
			
			c.addWaitingTime();
			if(!c.isMoved())
				c.addIdleTime();
			else
				c.setMoved(false);
			
			
			if(c.getCurPos().getEnd().equals(c.getDestPos().getStart()) && !c.getCurPos().getStart().equals(c.getDestPos().getEnd()) ){
				c.setTargetStreet(c.getDestPos());
				c.setRouteWeight(0);
			}
			else
			{
				
				ArrayList<Street> banList = new ArrayList<Street>();
				banList.add(new Street(c.getCurPos().getEnd(), c.getCurPos().getStart()));
				
				
				List<DefaultWeightedEdge> route = GraphUtility.findRoute(graph, c.getCurPos().getEnd(), c.getDestPos().getStart(), banList);
				
				if(route.size() == 0)
					route = GraphUtility.findRoute(graph, c.getCurPos().getEnd(), c.getDestPos().getEnd(), banList);
				
				if(route.size() > 0){
					final DefaultWeightedEdge first = route.get(0);
					c.setTargetStreet(new Street(graph.getEdgeSource(first), graph.getEdgeTarget(first)));
					c.setRouteWeight(routeWeight(route));
				}
			}
			
		}
		
		agent.addBehaviour(new MasterBehaviour(agent));
	}
	
	private int routeWeight(List<DefaultWeightedEdge>route){
		int cont = 0;
		for(DefaultWeightedEdge e: route)
			cont += graph.getEdgeWeight(e);
		return cont;
	}

}
